package com.sqy.controller;


import com.sqy.exception.ImoocMallException;
import com.sqy.exception.ImoocMallExceptionEnum;
import com.sqy.utlis.ApiResult;
import com.sqy.utlis.Constant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Api(tags = "上传图片模块")
public class ImgUpload {


    @PostMapping("/upload/file")
    @ApiOperation("上传图片")
    public ApiResult upload(@RequestParam("file") MultipartFile file,
                            HttpServletRequest request
    ) throws ImoocMallException {

        String filename = file.getOriginalFilename();
        //获取后缀名
        String suffixName = filename.substring(filename.lastIndexOf("."));
        //生成文件名称UUID
        UUID uuid = UUID.randomUUID();
        //生成新的文件名
        String newFileName = uuid.toString() + suffixName;

        //创建文件夹
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);

        if (!fileDirectory.exists()) {
            if (!fileDirectory.mkdir()) {
                throw new ImoocMallException(ImoocMallExceptionEnum.DELETE_FAILED);
            }
        }

        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + newFileName;
            return ApiResult.success(url);
        } catch (Exception e) {
            return ApiResult.error(ImoocMallExceptionEnum.UPLOAD_FAILED);
        }
    }

}
